package com.nd.realm;


import com.nd.dao.AdminMapper;
import com.nd.dao.PermissionMapper;
import com.nd.pojo.bean.Admin;
import com.nd.pojo.bean.AdminExample;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;



public class AdminRealm extends AuthorizingRealm {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    PermissionMapper permissionMapper;

    //登录验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MallToken token = (MallToken) authenticationToken;
        String username = token.getUsername();
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andUsernameEqualTo(username);
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        //用户不存在，抛出空指针
//        if(admins.size() == 0) return null;
        Admin admin = admins.get(0);
        //更新用户的最新登录时间
        admin.setLastLoginTime(new Date());
        adminMapper.updateByPrimaryKeySelective(admin);
        //加盐
        ByteSource salt = ByteSource.Util.bytes(username);
        return new SimpleAuthenticationInfo(admin,admin.getPassword(),salt,this.getName());
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Admin admin = (Admin) principalCollection.getPrimaryPrincipal();
        Integer[] roleIds = admin.getRoleIds();
        List<String> perms = new ArrayList<>();
        for (Integer roleId : roleIds) {
            List<String> permsById = permissionMapper.selectPermsById(roleId);
            perms.addAll(permsById);
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }


}
